package com.hertz.appr.http;

import java.util.HashMap;
import java.util.Iterator;

import org.apache.commons.httpclient.HostConfiguration;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;


public class HttpClientUtil {
	private static final Logger logger = Logger.getLogger(HttpClientUtil.class);

	private MultiThreadedHttpConnectionManager httpClientManager;

	private HttpClient httpClient;

	private static HttpClientUtil _instance;

	/**
	 * 获取实例
	 * 
	 * @return
	 * @throws Exception
	 */
	public static HttpClientUtil getInstance() throws Exception {
		if (_instance == null) {
			synchronized (HttpClientUtil.class) {
				if (_instance == null) {
					_instance = new HttpClientUtil();
				}
			}
		}
		return _instance;
	}

	private HttpClientUtil() throws Exception {
		init();
	}

	private void init() throws Exception {
		httpClientManager = new MultiThreadedHttpConnectionManager();
		HttpConnectionManagerParams params = httpClientManager.getParams();
		params.setStaleCheckingEnabled(true);
		params.setMaxTotalConnections(320);
		params.setDefaultMaxConnectionsPerHost(160);
		params.setConnectionTimeout(3000);
		params.setSoTimeout(3000);

		httpClient = new HttpClient(httpClientManager);
	}

	
	public PostMethod post(HttpClientUrl photoBlogUrl) throws Exception {

		if (photoBlogUrl == null)
			return null;

		HostConfiguration config = new HostConfiguration();
		config.setHost(photoBlogUrl.getHost(), photoBlogUrl.getPort());

		PostMethod post = new PostMethod(photoBlogUrl.getPath());
		setParams(photoBlogUrl.getParams(), post);

		int result = httpClient.executeMethod(config, post);

		logger.warn("HttpClient.executeMethod returns result = [" + result
				+ "]");
		logger.debug("HttpClient.executeMethod returns xml :");
		logger.debug(post.getResponseBodyAsString());

		if (result != 200)
			throw new Exception("wrong HttpClient.executeMethod post method !");

		return post;
	}

	/**
	 * web api 调用
	 * 
	 * @param photoBlogUrl
	 * @throws Exception
	 */
	public GetMethod get(HttpClientUrl photoBlogUrl) throws Exception {

		if (photoBlogUrl == null)
			return null;

		HostConfiguration config = new HostConfiguration();
		config.setHost(photoBlogUrl.getHost(), photoBlogUrl.getPort());

		GetMethod get = new GetMethod(photoBlogUrl.getPath());
		setParams(photoBlogUrl.getParams(), get);

		int result = httpClient.executeMethod(config, get);

		logger.warn("HttpClient.executeMethod returns result = [" + result
				+ "]");
		logger.debug("HttpClient.executeMethod returns xml :");
		logger.debug(get.getResponseBodyAsString());

		if (result != 200)
			throw new Exception("wrong HttpClient.executeMethod get method !");

		return get;
	}
  public GetMethod get(String url) throws Exception {
    if (StringUtils.isEmpty(url)) {
      return null;
    }
    GetMethod get = new GetMethod(url);
    int result = httpClient.executeMethod(get);
    logger.warn("HttpClient.executeMethod returns result = [" + result + "]");
    logger.debug("HttpClient.executeMethod returns xml :");
    logger.debug(get.getResponseBodyAsString());

    if (result != 200)
      throw new Exception("wrong HttpClient.executeMethod get method !");
    return get;
  }
	// ------------------------------------------------PRIVATE METHODS
	/**
	 * 从HashMap中生成参数列表
	 */
	private void setParams(HashMap params, PostMethod post) {
		if (params != null && params.size() > 0) {
			Iterator keys = params.keySet().iterator();
			while (keys.hasNext()) {
				String key = (String) keys.next();
				post.addParameter(key, (String) params.get(key));
			}
		}
	}

	/**
	 * 从HashMap中生成参数列表
	 */
	private void setParams(HashMap params, GetMethod get) {
		StringBuffer strParams = new StringBuffer();

		if (params != null && params.size() > 0) {
			Iterator keys = params.keySet().iterator();
			while (keys.hasNext()) {
				String key = (String) keys.next();
				strParams.append(key);
				strParams.append("=");
				strParams.append(params.get(key));
				strParams.append("&");
			}
		}

		// 删除最后一个'&'
		if (strParams.lastIndexOf("&") == strParams.length())
			strParams.deleteCharAt(strParams.length());
		logger.warn("params="+strParams.toString());
		get.setQueryString(strParams.toString());
	}
}
